/*
 * StoreDAO.java
 *
 * Created on March 5, 2007, 8:09 PM
 *
 */

package edu.byu.isys413.group1E.data;

import edu.byu.isys413.group1E.*;
import java.sql.*;
import java.util.ArrayList;

/** Reads and writes StoreBO data to and from the database.
 *
 * @author Travis Kulbeth
 */
public class StoreDAO {
    
    /** Contains an instance of StoreDAO*/
    private static StoreDAO instance = null;
    
    /** Creates a new instance of StoreDAO */
    public StoreDAO() {
    }
    
    /**Retrieves an instance of the StoreDAO object
     *
     * @return a current singleton instance of the StoreDAO class
     */
    public static synchronized StoreDAO getInstance() {
        if (instance == null) {
            instance = new StoreDAO();
        }
        return instance;
    }
    
    ///////////////////////////////////////////////////////////////////////////////
    /////////   CREATE
    /**
     * Creates a new StoreBO object with a newly generated GUID.
     *
     * @return a newly created StoreBO with unique GUID
     * @throws java.lang.Exception to catch any errors in the creation process.
     */
    public StoreBO create() throws Exception{
        String id = GUID.generate();
        StoreBO bo = new StoreBO(id);
        Cache c = Cache.getInstance();
        c.put(bo.getStoreID(), bo);
        return bo;
    }
    
    //////////////////////////////////////////////////////////////////////////////
    //////////   READ
    /**
     * This is the public read statement.  It loads an existing Store record
     * from the database based on the Store id and returns a StoreBO.
     *
     * @return a StoreBO containing the information extracted from the requested
     * tuple in the DB.
     * @param id contains the unique identifier for the record to be read from the DB.
     * @throws edu.byu.isys413.group1E.DataException to catch any errors with the incoming data
     * @throws edu.byu.isys413.group1E.ConnectionPoolException to catch errors when connecting to the DB
     */
    public synchronized StoreBO read(String id) throws DataException, ConnectionPoolException {
        // check to see if id in the cache
        Cache c = Cache.getInstance();
        StoreBO store = (StoreBO)c.get(id);
        if (store != null){
            return store;                                                        // if so, return it immediately
        }
        
        //otherwise, get it from the database
        try {
            Connection conn = ConnectionPool.getInstance().get();             // retrieve a database connection from the pool
            store = this.read(id, conn);                                              // call read with a connection
            conn.commit();
            ConnectionPool.getInstance().release(conn);                       // release the connection
        }catch (SQLException e) {
            //rollback
            throw new DataException("Could not retrieve record for id = " + id, e);
        }catch (ConnectionPoolException x) {
            //rollback
            throw new ConnectionPoolException("Could not establish connection to database.", x);
        }
        
        // release the connection back to the pool
        return store;
    }
    
    
    /**
     * This is the public read statement.  It loads an existing Store record
     * from the database based on the Store id, using an already existing connection to the DB,
     * and returns a StoreBO.
     * 
     * @return StoreBO
     * @param id contains the given id for the Store to be read
     * @param conn contains an already open connection to the DB
     * @throws edu.byu.isys413.group1E.DataException catches any errors with incoming data
     * @throws java.sql.SQLException catches any errors from the SQL execution
     */
    synchronized StoreBO read(String id, Connection conn) throws SQLException, DataException {
        // check to see if id in the cache
        Cache c = Cache.getInstance();
        StoreBO store = (StoreBO)c.get(id);
        if (store != null){
            return store;                                                        // if so, return it immediately
        }
        
        // if not in the cache, get a result set from
        // a SELECT * FROM table WHERE id=guid
        Statement stmt = conn.createStatement();
        ResultSet rs = stmt.executeQuery("SELECT * FROM Store WHERE StoreID = '" + id + "'");
        conn.commit();
        
        //build the object from the result set
        if (rs.next()) {
            store = new StoreBO(rs.getString("StoreID"));
            store.setAddress(rs.getString("Address"));
            store.setCity(rs.getString("City"));
            store.setState(rs.getString("State"));
            store.setZip(rs.getString("Zip"));
            store.setPhone(rs.getString("Phone"));
            store.setManagerID(rs.getString("ManagerID"));
            store.setAlreadyInDB(true);
            store.setIsDirty(false);
            
            // save to the cache
            c.put(store.getStoreID(), store);
        }else{
            throw new DataException("Object was not found in the database.");
        }
        stmt.close();
        // return the BO
        return store;
    }
    
    
    /**This is a public method to retrieve a list of all Stores in the DB.
     *
     * @throws edu.byu.isys413.group1E.DataException catches any errors with incoming data
     * @throws java.sql.SQLException catches any errors with SQL execution
     * @throws edu.byu.isys413.group1E.ConnectionPoolException catches any errors when connecting to the DB.
     * @return a list of all Stores from the DB.
     */
    public synchronized ArrayList<StoreBO> readAllStores() throws DataException, SQLException, ConnectionPoolException{
        ArrayList<StoreBO> storeList = new ArrayList<StoreBO>();
        //now build the query
        String query = "SELECT * FROM Store";
        
        Connection conn = ConnectionPool.getInstance().get();
        Statement stmt = conn.createStatement();
        ResultSet rs = stmt.executeQuery(query);
        conn.commit();
        
        //extract the elements from the result set and build a list of results
        //build the object from the result set
        while (rs.next()) {
            StoreBO store = new StoreBO(rs.getString("StoreID"));
            store.setAddress(rs.getString("Address"));
            store.setCity(rs.getString("City"));
            store.setState(rs.getString("State"));
            store.setZip(rs.getString("Zip"));
            store.setPhone(rs.getString("Phone"));
            store.setManagerID(rs.getString("ManagerID"));
            store.setAlreadyInDB(true);
            store.setIsDirty(false);
            
            // save to the list
            storeList.add(store);
        }//while
        
        stmt.close();
        ConnectionPool.getInstance().release(conn);
        return storeList;
    }
    
    //////////////////////////////////
    ///   UPDATE
    
    /** This is the public save method.  It is what is called when
     * the user (controller) wants to save or update an object
     * into the database.
     *
     * @param storeIn is a StoreBO object to be saved
     *
     * @throws edu.byu.isys413.group1E.DataException catches any errors with incoming data
     * @throws edu.byu.isys413.group1E.ConnectionPoolException catches any errors when connecting to the DB.
     */
    public synchronized void save(StoreBO storeIn) throws DataException, ConnectionPoolException {
        
        try {
            Connection conn = ConnectionPool.getInstance().get();
            try {
                this.save(storeIn, conn);                                   // call save with a connection
                conn.commit();
            } catch (SQLException ex) {
                conn.rollback();
                ex.printStackTrace();
                throw new SQLException();
            } catch (DataException ex) {
                conn.rollback();
                ex.printStackTrace();
            } catch (ConnectionPoolException ex) {
                conn.rollback();
                ex.printStackTrace();
            }
            ConnectionPool.getInstance().release(conn);                       // release the connection
        }catch (SQLException e) {
            throw new DataException("Error saving record for Store ID =" + storeIn.getStoreID(), e);
        }catch (ConnectionPoolException x){
            throw new ConnectionPoolException("Could not establish connection to database.", x);
        }
        
        // release the connection back to the pool
        return;
    }
    
    /** This is a package method that is called by the public save (above) or
     *  by another DAO.  Either way we already have a connection to the database
     *  to use.  The user (controller) code never calls this one directly, since
     *  it can't know about Connection objects or SQLExceptions.
     *
     *  By having other DAOs call this save method (rather than update or
     *  insert below, each DAO in a chained save (like the StoreDAO calling
     *  MembershipDAO calling InterestDAO save chain) can independently decide
     *  whether to udpate or insert the BO it's saving.
     *
     * @param store contains the StoreBO to be saved
     * @param conn contains the Connection that has been established to the DB
     *
     * @throws edu.byu.isys413.group1E.DataException catches any errors with incoming data
     * @throws java.sql.SQLException catches any errors with SQL execution
     * @throws edu.byu.isys413.group1E.ConnectionPoolException catches any errors when connecting to the DB.
     */
    synchronized void save(StoreBO store, Connection conn) throws SQLException, DataException, ConnectionPoolException {
        // run update or insert
        if (store.isIsDirty()) {
            if (store.isAlreadyInDB()) {
                update(store, conn);
            }else{
                insert(store, conn);
            }
            // set the dirty flag to false now that we've saved it
            store.setIsDirty(false);
        }
        
        
        // touch the cache for the object
        Cache c = Cache.getInstance();
        c.put(store.getStoreID(), store);
    }
    
    /**
     * This method is really a part of save(bo, conn) above.  It could be
     * embedded directly in it, but I've separated it into it's own method
     * to isolate the SQL udpate statement and make it more readable.  But
     * logically, it's really just a part of save.
     * 
     * @param store contains the StoreBO to be updated to the DB
     * @param conn contains the connection already established with the DB
     * @throws edu.byu.isys413.group1E.DataException catches any errors with incoming data
     * @throws java.sql.SQLException catches any errors with SQL execution
     */
    private synchronized void update(StoreBO store, Connection conn) throws SQLException, DataException {
        //update the DB
        PreparedStatement pstmt = conn.prepareStatement("UPDATE Store SET Address = ?, City = ?, State = ?, " +
                "Zip = ?, Phone = ?, ManagerID = ? WHERE StoreID = ?");
        pstmt.setString(1, store.getAddress());
        pstmt.setString(2, store.getCity());
        pstmt.setString(3, store.getState());
        pstmt.setString(4, store.getZip());
        pstmt.setString(5, store.getPhone());
        pstmt.setString(6, store.getManagerID());
        pstmt.setString(7, store.getStoreID());
        pstmt.executeUpdate();
        pstmt.close();
        store.setAlreadyInDB(true);
    }
    
    /**
     * This method is really a part of save(bo, conn) above.  It could be
     * embedded directly in it, but I've separated it into it's own method
     * to isolate the SQL insert statement and make it more readable.  But
     * logically, it's really just a part of save.
     * 
     * @param store contains the StoreBO to be updated to the DB
     * @param conn contains the connection already established with the DB
     * @throws edu.byu.isys413.group1E.DataException catches any errors with incoming data
     * @throws java.sql.SQLException catches any errors with SQL execution
     */
    private synchronized void insert(StoreBO store, Connection conn) throws SQLException, DataException {
        //update the DB
        PreparedStatement pstmt = conn.prepareStatement("INSERT INTO Store (StoreID, Address, City, State, " +
                "Zip, Phone, ManagerID) VALUES (?, ?, ?, ?, ?, ?, ?)");
        pstmt.setString(1, store.getStoreID());
        pstmt.setString(2, store.getAddress());
        pstmt.setString(3, store.getCity());
        pstmt.setString(4, store.getState());
        pstmt.setString(5, store.getZip());
        pstmt.setString(6, store.getPhone());
        pstmt.setString(7, store.getManagerID());
        pstmt.executeUpdate();
        pstmt.close();
        // tell the object that it's now in the db (so we call update next time not insert)
        store.setAlreadyInDB(true);
    }
    
    
    ///////////////////////////////////////////////////////////////////////////////
    /////////   DELETE
    /** I did not include the DELETE functionality intentionally due to instructions received, as well as
     * to protect the integrity of the data.
     */
    
}
